package com.example.mqmanager.controller;

import com.example.mqmanager.service.FileManagerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/file")
@CrossOrigin(origins = "*")
public class FileManagerController {

    private static final Logger logger = LoggerFactory.getLogger(FileManagerController.class);

    @Autowired
    private FileManagerService fileManagerService;

    /**
     * 分页读取文件内容
     * 
     * @param filePath 文件路径
     * @param page 页码（从1开始）
     * @param pageSize 每页行数
     * @return 文件内容和分页信息
     */
    @GetMapping("/content")
    public ResponseEntity<?> getFileContent(
            @RequestParam String filePath,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "200") int pageSize) {
        try {
            Map<String, Object> result = fileManagerService.getFileContent(filePath, page, pageSize);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("读取文件内容时出错: " + filePath, e);
            Map<String, Object> error = new HashMap<>();
            error.put("error", "读取文件内容时出错: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    /**
     * 获取文件信息
     * 
     * @param filePath 文件路径
     * @return 文件信息
     */
    @GetMapping("/info")
    public ResponseEntity<?> getFileInfo(@RequestParam String filePath) {
        try {
            Map<String, Object> result = fileManagerService.getFileInfo(filePath);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("获取文件信息时出错: " + filePath, e);
            Map<String, Object> error = new HashMap<>();
            error.put("error", "获取文件信息时出错: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }
}